﻿namespace WebApplication1
{
    public class Taskdispatch
    {
        Dictionary<string, Action> directory = new Dictionary<string, Action>();
        Dictionary<string, bool> directory1 = new Dictionary<string, bool>();
        public Taskdispatch()
        {
        }
        /// <summary>
        /// 执行任务
        /// </summary>
        public void SchedulingTasks()
        {
            foreach (var item in directory)
            {
                if (directory1.ContainsKey(item.Key))
                {
                    if (directory1[item.Key])
                    {
                        item.Value.Invoke();
                    }
                }
            }
        }
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="TaskName"></param>
        public void AddTask(string TaskName)
        {
            Type myType = typeof(MyTask);
            System.Reflection.MethodInfo[] methodInfos = myType.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            var task = methodInfos.Single(t=>t.Name==TaskName);
              var Delegate_= Delegate.CreateDelegate(typeof(Action), new MyTask(), task);//创建委托
                directory.Add(TaskName, (Action)Delegate_);
                directory1.Add(TaskName, true);

         
        }
        /// <summary>
        /// 取消任务
        /// </summary>
        /// <param name="TaskName"></param>
        public void CancelTask(string TaskName)
        {
            if(directory1.ContainsKey(TaskName))
            directory1[TaskName]=false;
        }
    }
}
